<?php
/**
 * Created by PhpStorm.
 * User: liuhong
 * Date: 2018/11/9
 * Time: 上午10:39
 */

namespace Api\Controller;

use Api\Service\CartService;
use Api\Service\GoodsService;

class CartController extends LoginBaseController
{
    public function __construct()
    {
        parent::__construct();
    }

    public function addCart(){

        $goods_id=I('post.goods_id');
        $goods_num=I('post.goods_num');
        if($goods_num<1){
            $this->ajax(202,'商品数量不能小于1');
        }
        //查询出商品信息
        $goodsFiled='goods_name,shop_price,market_price';
        $goodsInfo=GoodsService::S()->findGoodsInfoByGoodsId($goods_id,$goodsFiled);
        if(!$goodsInfo){
            $this->ajax(202,'商品不存在');
        }
        //判断购物车是否存在该商品
        $where['uid']=$this->uid;
        $where['goods_id']=$goods_id;
        $userCart=CartService::S()->findCartByWhere($where,'goods_num');
        $addInfo['goods_id']=$goods_id;
        $addInfo['goods_name']=$goodsInfo['goods_name'];
        $addInfo['shop_price']=$goodsInfo['shop_price'];
        $addInfo['market_price']=$goodsInfo['market_price'];
        $addInfo['uid']=$this->uid;
        $addInfo['create_time']=date('Y-m-d H:i:s');
        if($userCart){//存在
            $addInfo['goods_num']=$goods_num+$userCart['goods_num'];
            $re=CartService::S()->updCartGoodsNum($this->uid,$goods_id,$addInfo['goods_num']);
        }else{
            $addInfo['goods_num']=$goods_num;
            $re=CartService::S()->addCart($addInfo);
        }
        if($re===false){
            $this->ajax(202,'添加购物车失败');
        }else{
            $this->ajax(200,'success');
        }
    }

    //查询购物车信息
    public function queryCart(){
        //$where['uid']=$this->uid;
        $cartInfo=CartService::S()->queryCart($this->uid,self::baseCartFiled());//查询购物车信息
        foreach ($cartInfo as $k=>$v){
            $cartInfo[$k]['goods_pic']=C('UPYUN_DOMAIN').$v['goods_pic'];
        }
        if(!$cartInfo){
            $this->ajax(202,'购物车是空空的');
        }
        $this->ajax(200,'success',$cartInfo);
    }

    //修改用户购物车信息
    public function saveCart(){
        $goods_id=I('post.goods_id');
        $goods_num=I('post.goods_num');
        $cart_id=I('post.cart_id');
        $re=CartService::S()->updCartGoodsNum($this->uid,$goods_id,$goods_num);
        if($re===false){
            $this->ajax(202,'修改失败');
        }else{
            $this->ajax(200,'修改成功');
        }
    }

    public function baseCartFiled(){
        return $filed='cart_id,uid,goods_num,waoo_goods.goods_id,waoo_goods.goods_name,waoo_goods.market_price,waoo_goods.shop_price,waoo_goods.goods_pic';
    }

    public function delCart(){
        $where['cart_id']=array('in',I('post.cart_ids'));
        $where['uid']=$this->uid;
        $delRe=CartService::S()->delCartByWhere($where);
        if($delRe){
            $this->ajax(200,'success');
        }else{
            $this->ajax(200,'error');
        }
    }

}